<template>
  <div class="text-tooltip">
    <el-tooltip class="item" effect="dark" :disabled="isShowTooltip" :placement="placement">
      <div v-html="showContent(html)" slot="content" class="showTip"></div>
      <p class="over-flow" :class="className" @mouseover="onMouseOver(refName)">
        <span :ref="showContent(refName)">{{showContent(content)}}</span>
      </p>
    </el-tooltip>
  </div>
</template>

<script>
export default {
  name: 'textTooltip',
  props: {
    placement:{
      type:String,
      default:'top'
    },
    // 显示的文字内容
    html: {
      type: String | Number | Object,
      default: () => {
        return ''
      }
    },
    content: {
      type: String | Number | Object,
      default: () => {
        return ''
      }
    },
    // 外层框的样式，在传入的这个类名中设置文字显示的宽度
    className: {
      type: String,
      default: () => {
        return ''
      }
    },
    // 为页面文字标识（如在同一页面中调用多次组件，此参数不可重复）
    refName: {
      type: String | Number | Object,
      default: () => {
        return ''
      }
    },
    // html、content、refName三合一
    copyText: {
      type: String | Number | Object,
      default: () => {
        return ''
      }
    }
  },
  data () {
    return {
      isShowTooltip: true,
      errorList: [null, undefined, NaN, '']
    }
  },
  methods: {
    onMouseOver (data) {
      let str = this.errorList.includes(this.copyText) ? data : this.copyText
      let parentWidth = this.$refs[str].parentNode.offsetWidth
      let contentWidth = this.$refs[str].offsetWidth
      // 判断是否开启tooltip功能
      if (contentWidth > parentWidth) {
        this.isShowTooltip = false
      } else {
        this.isShowTooltip = true
      }
    },
    // 根据收到的类型显示内容
    showContent (data) {
      let val = this.errorList.includes(this.copyText) ? data : this.copyText
      if (this.errorList.includes(val)) {
        return ''
      } else if ((typeof val) === 'object') {
        return val.join(',')
      } else {
        return val
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.over-flow {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.wid190 {
  width: 100%;
}
.spanText {
  display: inline;
  .el-tooltip {
    display: inline;
  }
}
p {
  margin: 0;
}
.showTip {
  max-width: 600px;
}
</style>
